import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select,
  message
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useSearchParams } from 'react-router-dom'
import { useState, useEffect } from 'react'
import './index.scss'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { createArticleApi, getArticleByIdApi, editArticleByIdApi } from '../../apis/article'
import useChannels from '../../hooks/useChannels'
const { Option } = Select
const Publish = () => {
  const [searchParams] = useSearchParams()
  const articleId = searchParams.get('id')
  const { channelList } = useChannels()
  const [fileList, setFileList] = useState([])
  const [ form ] = Form.useForm()
  useEffect(() => {
    async function getArticleById() {
      const res = await getArticleByIdApi(articleId)
      // 回填基础内容
      form.setFieldsValue(res.data)
      // 回填文章类型
      form.setFieldValue('type', res.data.cover.type)
      setType(res.data.cover.type)
      // 回填图片信息
      setFileList(res.data.cover.images.map(url => ({ url })))
    }
    if (articleId) getArticleById()
  }, [articleId, form])
  const handlePicChange = ({file, fileList}) => {
    console.log(fileList)
    setFileList(fileList)
  }

  const [type, setType] = useState(0)
  const handleTypeChange = (value) => {
    const type = value.target.value
    setType(type)
  }

  const handleSubmit = async (value) => {
    if (type !== fileList.length) return message.warning('封面类型与数量不匹配')
    const { title, content, channel_id } = value
    const reqData = {
      title,
      content,
      cover: {
        type,
        images: fileList.map(item => item.url || item.response.data.url)
      },
      channel_id
    }
    if (articleId) {
      await editArticleByIdApi(reqData, articleId)
      message.success('文章修改成功')
    } else {
      await createArticleApi(reqData)
      message.success('文章发布成功')
    }

  }
  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb 
            separator=">" 
            items={[
              {
                title: <Link to="/home">首页</Link>
              },
              {
                title: `${articleId ? '编辑': '发布'}文章`
              }
            ]}
          />
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 0 }}
          onFinish={handleSubmit}
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {
                channelList.map(item => <Option key={item.id} value={item.id}>{item.name}</Option>)
              }
            </Select>
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={handleTypeChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {
              type > 0 &&
              <Upload
                name="image"  //调接口是参数字段,值类型为文件流binary
                listType="picture-card"
                className="avatar-uploader"
                showUploadList
                action={'http://geek.itheima.net/v1_0/upload'}
                onChange={handlePicChange}
                maxCount={type}
                fileList={fileList}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            }
            
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {articleId ? '修改': '发布'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish